# coding: utf-8

# -------------------------------------------------------------------------------
# Name:         utils.py
# Description:
# Author:       XiangjunZhao
# EMAIL:        2419352654@qq.com
# Date:         2020/10/27 17:04
# -------------------------------------------------------------------------------
import json
import logging
import re

from apps.SystemService.models import Parameter
from apps.CeleryScheduledTaskService.SystemService.send_mail_task import send_mail
from utils.dingtalk_client import DingTalkClient

logger = logging.getLogger(__name__)

# 绝对http url正则表达式
absolute_http_url_regexp = re.compile(r"^https?://", re.I)


def send_testreport(report_type, version):
    """
    发送测试报告
    Args:
        report_type: 报告类型（testcase、testsuite）
        version: 版本号

    Returns:

    """
    report_parameter = Parameter.objects.filter(key='REPORT', is_deleted=False).first()
    if report_parameter:
        value = json.loads(report_parameter.value)
        if value:
            # 访问地址
            url = value.get('URL')
            if url:
                if not absolute_http_url_regexp.match(url.lower()):
                    url = 'http://' + url.lstrip('/')
                url = url.rstrip('/')
            report = '{url}/#/QAPlatform/HttpAutoTestService/report/{report_type}/{version}'.format(url=url,
                                                                                                    report_type=report_type,
                                                                                                    version=version)

            # 是否发送报告(邮件)
            send_email_report = value.get('SEND_EMAIL_REPORT')
            if send_email_report:
                # 收件人
                to = value.get('TO')
                # 抄送人
                cc = value.get('CC')
                if not to:
                    logger.warning('收件人为空，邮件发送测试报告失败')
                to = to.split(',')
                cc = cc.split(',') if cc else None
                try:
                    send_mail(subject='测试报告', body=report, to=to, cc=cc)
                except Exception as e:
                    logger.error(f'邮件发送测试报告失败，原因：{e}')
                    raise e
                else:
                    logger.info('邮件发送测试报告成功')

            # 是否发送报告(钉钉)
            send_dingtalk_report = value.get('SEND_DINGTALK_REPORT')
            if send_dingtalk_report:
                dingtalk_parameter = Parameter.objects.filter(key='DINGTALK', is_deleted=False).first()
                if dingtalk_parameter:
                    value = json.loads(dingtalk_parameter.value)
                    if value:
                        webhook = value.get('WEBHOOK')
                        secret = value.get('SECRET') or None
                        if webhook:
                            try:
                                dingtalk = DingTalkClient(webhook=webhook, secret=secret)
                                dingtalk.send_link(title='测试报告', text=report, message_url=report)
                            except Exception as e:
                                logger.error(f'钉钉发送测试报告失败，原因：{e}')
                                raise e
                            else:
                                logger.info('钉钉发送测试报告成功')
                        else:
                            logger.warning('webhook为空，钉钉发送测试报告失败')
